<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="queryMyCustomerProjectList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openInsertDialog">新增项目</el-button>
      </template>
      <template #projectName="scope">
        <el-button type="primary" link @click="toProjectDetail(scope.row)"> {{ scope.row.projectName }}</el-button>
      </template>
      <template #createDate="scope">
        {{ scope.row.createDate.replace("T", " ").split(".")[0] }}
      </template>
      <template #updateDate="scope">
        {{ scope.row.updateDate.replace("T", " ").split(".")[0] }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="openUpdateDialog(scope.row)"> 编辑 </el-button>
        <el-button type="primary" link :icon="View" @click="commitAwaitPreview(scope.row)" v-if="scope.row.projectStatus === 0">
          提交审核
        </el-button>
      </template>
    </ProTable>
    <!-- 新增对话框 -->
    <el-dialog width="30%" title="创建新项目" v-model="insertDialogVisible">
      <el-form ref="insertFormRef" :model="insertParam" :rules="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="insertParam.projectName"></el-input>
        </el-form-item>
        <el-form-item label="项目编码" prop="orderName">
          <el-input v-model="insertParam.projectNumber"></el-input>
        </el-form-item>
        <el-form-item label="客户" prop="customersId">
          <el-select v-model="insertParam.customersId" @change="insertChangeFilter">
            <el-option
              v-for="item in customers"
              :key="item.customersId"
              :value="item.customersId"
              :label="item.customersName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="insertParam.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="insertDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addCustomerProject(insertFormRef)">创建</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog width="30%" title="修改项目信息" v-model="updateDialogVisible">
      <el-form ref="updateFormRef" :model="updateParam" :rules="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-form-item label="项目名称" prop="orderNumber">
          <el-input v-model="updateParam.projectName"></el-input>
        </el-form-item>
        <el-form-item label="项目编码" prop="orderName">
          <el-input v-model="updateParam.projectNumber"></el-input>
        </el-form-item>
        <el-form-item label="客户" prop="customersId">
          <el-select v-model="updateParam.customersId" @change="updateChangeFilter">
            <el-option
              v-for="item in customers"
              :key="item.customersId"
              :value="item.customersId"
              :label="item.customersName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单备注">
          <el-input v-model="updateParam.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateCustomerProject(updateFormRef)"> 修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="myProject">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  CirclePlus,
  Delete,
  EditPen,
  Download,
  Upload,
  View,
  Refresh,
  ElementPlus,
  More,
  Picture
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import ProTable from "@/components/ProTable/index.vue";
import UploadImg from "@/components/Upload/Img.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { HxCustomers } from "@/api/interface/customers";
import { queryCustomers } from "@/api/modules/customers";

import { useRoute } from "vue-router";
import { CreateCustomerProjectParam, CustomerProjectResult, EditCustomerProjectInfoParam } from "@/api/interface/customerProject";
import {
  createCustomerProject,
  editCustomerProjectInfo,
  editCustomerProjectStatus,
  queryMyCustomerProjectList
} from "@/api/modules/customerProject";
import { customerProjectStatusEnum, statusFieldNames } from "@/enums/httpEnum";

const router = useRouter();

const proTable = ref<ProTableInstance>();

/** 新增对话框是否可见 */
const insertDialogVisible = ref(false);

/** 修改对话框是否可见 */
const updateDialogVisible = ref(false);

/** 新增表单Form */
const insertFormRef = ref<FormInstance>();

/** 修改表单Form */
const updateFormRef = ref<FormInstance>();

/** 新增初始化参数 */
const initInsertParam = {
  projectName: "",
  customersId: ""
};

/** 新增参数 */
const insertParam = reactive<CreateCustomerProjectParam>({
  projectName: "",
  customersId: ""
});

/** 修改参数 */
const updateParam = reactive<EditCustomerProjectInfoParam>({
  projectId: "",
  projectName: "",
  customersId: ""
});

/** 客户列表 */
let customers = ref<HxCustomers[]>([]);

/** form表单验证规则 */
const ruleForm = reactive<FormRules>({
  projectName: [{ required: true, message: "请输入项目名称", trigger: "change" }],
  customersId: [{ required: true, message: "请选择客户", trigger: "change" }]
});

/** 表格配置项 */
const columns = reactive<ColumnProps<CustomerProjectResult>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { type: "index", label: "", width: 80 },
  {
    prop: "projectNumber",
    label: "项目编号",
    width: 150,
    search: { el: "input", tooltip: "请输入项目编号" }
  },
  {
    prop: "projectName",
    label: "项目名称",
    width: 120,
    search: { el: "input", tooltip: "请输入项目名称" }
  },

  {
    prop: "projectStatus",
    label: "项目状态",
    tag: true,
    enum: customerProjectStatusEnum,
    search: { el: "select", props: { filterable: true } },
    fieldNames: statusFieldNames
  },
  {
    prop: "customerName",
    label: "客户名称"
  },
  {
    prop: "createDate",
    label: "创建时间",
    width: 200
  },
  {
    prop: "createUser",
    label: "创建人",
    width: 120
  },
  {
    prop: "previewDate",
    label: "审核时间",
    width: 120
  },
  {
    prop: "previewUser",
    label: "审核人",
    width: 120
  },
  { prop: "operation", label: "操作", fixed: "right", width: 200 }
]);

/** 创建订单选择客户时填入客户信息 */
const insertChangeFilter = (val: string) => {
  if (val) {
    insertParam.customersId = customers.value.find(p => p.customersId == val)!.customersId;
  }
};

/** 修改订单时选择客户填入客户信息 */
const updateChangeFilter = (val: string) => {
  if (val) {
    updateParam.customersId = customers.value.find(p => p.customersId == val)!.customersId;
  }
};

/** 初始化客户信息 */
const initCustomers = async () => {
  const { data } = await queryCustomers({});
  customers.value = [...data];
};

/** 打开新增对话框 */
const openInsertDialog = async () => {
  insertDialogVisible.value = true;
  await initCustomers();
};

/** 打开修改对话框 */
const openUpdateDialog = async (param: CustomerProjectResult) => {
  updateDialogVisible.value = true;
  Object.assign(updateParam, param);
  await initCustomers();
};

/** 新增项目 */
const addCustomerProject = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await createCustomerProject(insertParam);
      ElMessage.success("创建新项目成功");
      insertDialogVisible.value = false;
      Object.assign(insertParam, initInsertParam);
      proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

/** 修改项目 */
const updateCustomerProject = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await editCustomerProjectInfo(updateParam);
      ElMessage.success("修改项目信息成功");
      updateDialogVisible.value = false;
      Object.assign(insertParam, initInsertParam);
      proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

const commitAwaitPreview = async (param: CustomerProjectResult) => {
  ElMessageBox.confirm("是否提交审核?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    await editCustomerProjectStatus({ projectId: param.projectId, projectStatus: 1 });
    ElMessage.success("提交审核成功");
    proTable?.value?.getTableList();
  });
};

const toProjectDetail = (param: CustomerProjectResult) => {
  router.push(`/project/projectRecord/index?customerProjectId=${param.projectId}`);
};
</script>
